package com.src.xyzk_personal;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListPopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.src.xyzk_personal.config.Common;
import com.src.xyzk_personal.util.DeleteLogUtil;
import com.src.xyzk_personal.util.LanguageUtil;
import com.src.xyzk_personal.util.SharedPreferencesUtil;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class SettingActivity extends Activity {
    private static String TAG = "SettingActivity";
    Context context = SettingActivity.this;
    //锁定屏幕
    private PowerManager powerManager = null;
    private PowerManager.WakeLock wakeLock = null;
    private TextView m_showtext = null;
    private Button m_update = null;

    //设置
    private Spinner m_printselect = null;    //下拉菜单
    private ArrayList<String> m_printarray = null;
    private ArrayAdapter<String> m_printadapter = null;
    //通讯方式
    private Spinner m_comselect = null;    //下拉菜单
    private Spinner m_networkingselect = null; //联网模式的下拉菜单
    private ArrayList<String> m_netarray = null;
    private ArrayAdapter<String> m_netadapter = null;
    private ArrayList<String> m_comarray = null;
    private ArrayAdapter<String> m_comadapter = null;
    //server选择
    private Spinner m_serverselect = null;
    private ArrayList<String> m_serverarray = null;
    private ArrayAdapter<String> m_serveradapter = null;

    private boolean isUserInteracted = false; // 添加切换语言Spinner标志位
    private boolean isUserInteractedOnDeleteLog = false; // 添加删除特定时间日志Spinner标志位

    //缓存
    SharedPreferences.Editor m_editor = null;
    SharedPreferences m_pref = null;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.system_setting_activity);
        //锁定屏幕初始化
        powerManager = (PowerManager) this.getSystemService(Service.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Lock");

        //初始化缓存
        m_editor = this.getSharedPreferences("config", MODE_PRIVATE).edit(); //不存在则创建
        m_pref = getSharedPreferences("config", MODE_PRIVATE);
        //是否需计算锁的数量
        wakeLock.setReferenceCounted(false);
        //progress
        m_printselect = (Spinner) findViewById(R.id.Setting_print_select);
        m_printarray = new ArrayList<>();
        for (int i = 1; i < 6; i++)
            m_printarray.add(getResources().getString(R.string.printer) + i);
        m_printadapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, m_printarray);
        //设置下拉风格
        m_printadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        m_printselect.setAdapter(m_printadapter);
        // 设置初始位置为Common.Printnum值
        m_printselect.setSelection(Common.Printnum - 1);
        m_printselect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                // 更新Common.Printnum的值
                Common.Printnum = position + 1;
                // 保存打印机序号至SharedPreferences
                SharedPreferencesUtil.saveInt(getApplicationContext(), "intValueKey", Common.Printnum);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        //通讯方式
        m_comselect = (Spinner) findViewById(R.id.Setting_communication_select);
        m_comarray = new ArrayList<String>();
        m_comarray.add(getResources().getString(R.string.bluetooth_connection));
        m_comarray.add(getResources().getString(R.string.wired_connection));
        m_comadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_comarray);
        //设置下拉风格
        m_comadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        m_comselect.setAdapter(m_comadapter);
        m_comselect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                Common.Communication = arg2;
                m_editor.putInt("Communication", arg2);
                m_editor.commit();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });
        //获取默认值
        m_comselect.setSelection(Common.Communication);

        //todo  联网模式
        m_networkingselect = (Spinner) findViewById(R.id.Setting_Networking_select);
        m_netarray = new ArrayList<String>();
        m_netarray.add(getResources().getString(R.string.wired_connection));
        m_netarray.add(getResources().getString(R.string.not_connected_Internet));
        m_netadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_netarray);
        //设置下拉风格
        m_netadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        m_networkingselect.setAdapter(m_netadapter);
        m_networkingselect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                Common.isConnect= arg2 == 0;
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
        //获取默认值
        if (Common.isConnect){
            m_networkingselect.setSelection(0);
        }else {
            m_networkingselect.setSelection(1);
        }
        //mes模式
        m_serverselect = (Spinner) findViewById(R.id.Setting_webmes_select);
        m_serverarray = new ArrayList<String>();
        m_serverarray.add(getResources().getString(R.string.old_server));
        m_serverarray.add(getResources().getString(R.string.new_server));
        m_serveradapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_serverarray);
        //设置下拉风格
        m_serveradapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        m_serverselect.setAdapter(m_serveradapter);
        m_serverselect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                Common.web_enable = arg2 != 0;
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });
        //获取默认值
        if(!Common.web_enable)
            m_serverselect.setSelection(0);
        else
            m_serverselect.setSelection(1);

        initLanguageAndLogSpinner();
    }

    /**
     * 初始化切换语言和删除特定时间内日志的Spinner
     */
    private void initLanguageAndLogSpinner() {
        final Spinner languageSpinner = (Spinner) findViewById(R.id.language_spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.languages, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        languageSpinner.setAdapter(adapter);
        int position = 0;
        switch (SharedPreferencesUtil.getString(this, SharedPreferencesUtil.LANGUAGE, "en")) {
            case "en": {
                position = 0;
                break;
            }
            case "zh": {
                position = 1;
                break;
            }
            case "ru": {
                position = 2;
                break;
            }
        }
        languageSpinner.setSelection(position);
        languageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isUserInteracted) { // 检查是否是用户手动选择的
                    String selectedLanguage = "";
                    switch (position) {
                        case 0:
                            selectedLanguage = "en";
                            break;
                        case 1:
                            selectedLanguage = "zh";
                            break;
                        case 2:
                            selectedLanguage = "ru";
                            break;
                    }
                    LanguageUtil.changeLanguage(SettingActivity.this, selectedLanguage);
                } else {
                    isUserInteracted = true; // 设置为true，表示用户已经与Spinner互动
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        final Spinner deleteLogSpinner = (Spinner) findViewById(R.id.delete_log_spinner);
        ArrayAdapter<CharSequence> deleteLogAdapter = ArrayAdapter.createFromResource(this,
                R.array.deleteTimeLog, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        deleteLogSpinner.setAdapter(deleteLogAdapter);
        deleteLogSpinner.setSelection(0);
        deleteLogSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isUserInteractedOnDeleteLog) { // 检查是否是用户手动选择的
                    switch (position) {
                        case 0:
                            DeleteLogUtil.deleteLastSevenDaysLogs();
                            break;
                        case 1:
                            DeleteLogUtil.deleteLastThirtyDaysLogs();
                            break;
                        case 2:
                            DeleteLogUtil.deleteLastSixMonthsLogs();
                            break;
                    }
                } else {
                    isUserInteractedOnDeleteLog = true; // 设置为true，表示用户已经与Spinner互动
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    @Override
    protected void onStop() {
        super.onStop();
        isUserInteracted = false;
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        //请求常亮
        wakeLock.acquire();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        //取消屏幕常亮
        wakeLock.release();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    private final static int MSG_SHOW_TEXT_ID = 101;
    private final static int MSG_SHOW_TEXT = 102;
    private final static int MSG_INIT_PROGRESS = 103;
    private final static int MSG_SET_PROGRESS = 104;
    private final static int MSG_END_PROGRESS = 105;
    private Handler m_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SHOW_TEXT_ID:
                    m_showtext.setText(msg.arg1);
                    m_showtext.invalidate();
                    break;
                case MSG_SHOW_TEXT:
                    m_showtext.setText((CharSequence) msg.obj);
                    m_showtext.invalidate();
                    break;
                case MSG_END_PROGRESS:    //结束
                    m_update.setClickable(true);
                    break;
                default:
                    break;
            }
        }
    };
}


